package com.app.utils.util.view.expression.view;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.app.utils.util.ViewFrameUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.view.expression.ExpressionUtil;
import com.app.utils.util.view.expression.adapter.BQAdapter;
import com.app.utils.util.view.expression.adapter.PagerAdapterImg;
import com.app.utils.util.view.expression.bean.BiaoQin;
import com.app.utils.util.view.expression.bean.BiaoQinList;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 显示表情列表的控件
 *
 * @author xuxinghai
 */
public class BiaoQinLinearLayout extends LinearLayout implements OnItemClickListener,
        OnPageChangeListener {

    /**
     * 本控件用于显示表情列表，并且可显示在编辑框内，以下是用法讲解 创建完本控件后
     * 1.配置一些view参数 调用EditText msgView,View positionView, int numColumns,int selectImgId方法
     * 2.配置显示的表情数据调用addList(List<String> names, List<Integer> pics)方法，调用一次添加一页表情
     * 3.之后调用showOrHideView()方法进行显示
     */

    private List<View> pagerList;// ViewPager 的数据集
    protected List<BiaoQinList> list = new ArrayList<BiaoQinList>();// 每一页的表情集合
    private int numColumns = 5;// 显示表情的列数 默认5列
    private BiaoQinEditView msgEditView;// 表情添加到的EditView;
    private View positionView;// 决定表情展现位置的view 在该view之下
    private InputMethodManager inputManager;// 键盘操作工具
    private ViewPager mViewPager;// 表情显示的viewpager
    private RadioGroup mGradioGroup;// 表情页码
    private int selectImg = -1;// 没选中的页码图片资源id
    private Activity mActivity;//当前依附的activity

    public BiaoQinLinearLayout(Context context) {
        super(context);
    }

    public BiaoQinLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 初始化控件
     */
    private void initView(Context context) {
        // 移除所有子view
        removeAllViews();
        setOrientation(LinearLayout.VERTICAL);
        // 添加系那是表情的viewpager
        mViewPager = new ViewPager(context);

        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mViewPager.setLayoutParams(params);
        mViewPager.setOnPageChangeListener(this);
        addView(mViewPager);
        // 添加页码原点
        if (selectImg == -1) {
            // 如果没有设置图片资源id,则不显示选中图片
            return;
        }
        mGradioGroup = new RadioGroup(context);
        mGradioGroup.setOrientation(RadioGroup.HORIZONTAL);
        mGradioGroup.setGravity(Gravity.CENTER);
        addView(mGradioGroup);
    }

    /******************* 共外部调用的方法 start **************************/

    /**
     * 配置表情相关的view
     *
     * @param msgView      点击表情编辑添加的View
     * @param positionView 表情出现位置有关的view
     */
    public void configView(BiaoQinEditView msgView, View positionView,Activity activity) {
        this.msgEditView = msgView;
        this.positionView = positionView;
        this.mActivity = activity;
    }

    /**
     * 配置表情相关的view和列数
     *
     * @param msgView      点击表情编辑添加的View
     * @param positionView 表情出现位置有关的view
     * @param numColumns   展示表情的列数
     */
    public void configView(BiaoQinEditView msgView, View positionView, int numColumns,Activity activity) {
        this.msgEditView = msgView;
        this.positionView = positionView;
        this.numColumns = numColumns;
        this.mActivity = activity;
    }

    /**
     * 配置表情相关的view、列数、选中页面的资源id
     *
     * @param msgView      点击表情编辑添加的View
     * @param positionView 表情出现位置有关的view
     * @param numColumns   展示表情的列数
     * @param selectImgId  选中表情的图片资源id
     */
    public void configView(BiaoQinEditView msgView, View positionView, int numColumns,
                           int selectImgId,Activity activity) {
        this.msgEditView = msgView;
        this.positionView = positionView;
        this.numColumns = numColumns;
        this.selectImg = selectImgId;
        this.mActivity = activity;
    }

    /**
     * 添加表情（以一页表情为单位）
     *
     * @param maps 表情集合
     */
    public void addList(Map<String,Integer> maps,Map<String,String> names) {
        BiaoQinList bql = new BiaoQinList(maps,names);
        if (list != null) {
            list.add(bql);
        } else {
            list = new ArrayList<BiaoQinList>();
            list.add(bql);
        }
    }


    /**
     * 展示或者隐藏表情view
     */
    public void showOrHideView() {

        if (getVisibility() == View.VISIBLE) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    setVisibility(View.GONE);
                }
            }, 30);
            WindowManager.LayoutParams params = mActivity.getWindow().getAttributes();
            if (params.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) {
                params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
                mActivity.getWindow().setAttributes(params);
            }
            if (inputManager == null) {
                inputManager = (InputMethodManager) getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
            }
            if (inputManager != null && inputManager.isActive()) {
                inputManager.showSoftInput(msgEditView, 0);
            }

        } else {
            if (pagerList == null) {
                initData();
            }

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    setVisibility(View.VISIBLE);
                }
            }, 5);
            ViewFrameUtils.closeInputSoft(mActivity, msgEditView);
        }
    }


    /**
     * 配置表情追加的EditText控件
     *
     * @param editTextView
     */
    public void setMsgEditView(BiaoQinEditView editTextView) {
        this.msgEditView = editTextView;
    }

    /**
     * 配置每页表情显示的列数
     *
     * @param numColumns
     */
    public void setNumColumns(int numColumns) {
        this.numColumns = numColumns;
    }

    /**
     * 配置选中页面的索引图片
     *
     * @param selectImg
     */
    public void setSelectImgResourceId(int selectImg) {
        this.selectImg = selectImg;
    }

    /******************* 共外部调用的方法 end **************************/

    /**
     * 初始化
     */
    private void initData() {
        if (list == null) {
            return;
        }
        if (mViewPager == null || mGradioGroup == null) {
            initView(getContext());
        }
        pagerList = new ArrayList<View>();
        int space = (int)ViewSizeUtils.getHeightSize(40);
        for (int i = 0; i < list.size(); i++) {
            // 得到某一页的表情集合
            BiaoQinList bql = list.get(i);
            if (bql == null || bql.getList() == null) {
                continue;
            }
            // 构造第一组表情
            GridView gridview = new GridView(getContext());
            gridview.setNumColumns(numColumns);
            gridview.setVerticalSpacing(space);
            BQAdapter adapter1 = new BQAdapter(bql.getList(), getContext());
            gridview.setAdapter(adapter1);
            gridview.setOnItemClickListener(this);
            // 添加一页表情
            pagerList.add(gridview);
        }
        // 适配表情数据
        PagerAdapterImg pagerAdapter = new PagerAdapterImg(pagerList);
        mViewPager.setAdapter(pagerAdapter);
        // 如果配置了选中页面图片资源id则适配页码原点
        if (pagerList.size() > 1 && selectImg != -1) {
            for (int i = 0; i < pagerList.size(); i++) {
                RadioButton rb = new RadioButton(getContext());
                rb.setId(i);
                rb.setButtonDrawable(selectImg);
                rb.setPadding(5, 5, 5, 5);
                mGradioGroup.addView(rb);
                if (i == 0) {
                    mGradioGroup.check(i);
                }
            }
        }
        mGradioGroup.setVisibility(View.VISIBLE);
        // 计算本控件的高度
//        int[] locations = new int[2];
//        positionView.getLocationOnScreen(locations);
//        float viewOnHg = locations[1] + positionView.getHeight();
        int screenHeight = ViewSizeUtils.getHeightPixels();
        int height = (int) (screenHeight/3);
        getLayoutParams().height = height;
        mViewPager.getLayoutParams().height = height -  (int)ViewSizeUtils.getHeightSize(40);
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if (hasWindowFocus && pagerList == null) {
            //0.5秒后开始初始化表情数据
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    initData();
                }
            }, 500);

        }
    }

    /**
     * 点击表情的单击事件
     */
    @SuppressWarnings("ResourceType")
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long id) {

//        //如果按下的是删除 则删除文字
//        if(position == (parent.getCount()-1)){
//            msgEditView.delText();
//            return;
//        }
        BiaoQin bq = (BiaoQin) parent.getItemAtPosition(position);
        //获取资源图片显示在 评论中
        ExpressionUtil.matchExpression(getContext(), bq.getId(), bq.getResourcesId(), msgEditView);
    }


    /**********
     * viewpager 的页面改变监听 start
     *********/
    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageSelected(int arg0) {
        if (mGradioGroup != null) {
            mGradioGroup.check(arg0);
        }

    }
    /********** viewpager 的页面改变监听 end *********/

}
